package com.example.canvasdemo.ui

import retrofit2.Callback
import retrofit2.Response
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import retrofit2.Call
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.example.canvasdemo.LoginActivity
import com.example.canvasdemo.R
import com.example.canvasdemo.model.UpdateResponse
import com.example.canvasdemo.model.UpdateUserRequest
import com.example.canvasdemo.model.UserModel
import com.example.canvasdemo.network.ApiService
import com.example.canvasdemo.network.RetrofitClient

class ProfileFragment : Fragment() {

    private lateinit var usernameTextView: TextView
    private lateinit var scoreTextView: TextView
    private lateinit var emailTextView: TextView
    private lateinit var phoneTextView: TextView

    private lateinit var usernameEditText: EditText
    private lateinit var passwordEditText: EditText
    private lateinit var emailEditText: EditText
    private lateinit var phoneEditText: EditText

    private lateinit var editButton: Button
    private lateinit var saveButton: Button
    private lateinit var logoutButton: Button

    private var isEditing = false

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val view = inflater.inflate(R.layout.fragment_profile, container, false)

        // 初始化控件
        usernameTextView = view.findViewById(R.id.tvUsername)
        scoreTextView = view.findViewById(R.id.tvScore)
        emailTextView = view.findViewById(R.id.tvEmail)
        phoneTextView = view.findViewById(R.id.tvPhone)

        usernameEditText = view.findViewById(R.id.etUsername)
        passwordEditText = view.findViewById(R.id.etPassword)
        emailEditText = view.findViewById(R.id.etEmail)
        phoneEditText = view.findViewById(R.id.etPhone)

        editButton = view.findViewById(R.id.btnEdit)
        saveButton = view.findViewById(R.id.btnSave)
        logoutButton = view.findViewById(R.id.btnLogout)

        // 初始状态：隐藏编辑控件和保存按钮
        setEditMode(false)

        // 加载用户信息
        fetchUserData()

        // 编辑按钮逻辑
        editButton.setOnClickListener {
            toggleEditMode()
        }

        // 保存按钮逻辑
        saveButton.setOnClickListener {
            saveUserInfo()
        }

        // 退出按钮逻辑
        logoutButton.setOnClickListener {
            logout()
        }

        return view
    }

    /**
     * 切换编辑模式
     */
    private fun toggleEditMode() {
        isEditing = !isEditing
        setEditMode(isEditing)
    }

    /**
     * 设置编辑模式
     */
    private fun setEditMode(isEditing: Boolean) {
        if (isEditing) {
            // 显示编辑控件，隐藏 TextView
            usernameTextView.visibility = View.GONE
            emailTextView.visibility = View.GONE
            phoneTextView.visibility = View.GONE

            usernameEditText.visibility = View.VISIBLE
            passwordEditText.visibility = View.VISIBLE
            emailEditText.visibility = View.VISIBLE
            phoneEditText.visibility = View.VISIBLE

            saveButton.visibility = View.VISIBLE
            editButton.text = "取消"
        } else {
            // 显示 TextView，隐藏编辑控件
            usernameTextView.visibility = View.VISIBLE
            emailTextView.visibility = View.VISIBLE
            phoneTextView.visibility = View.VISIBLE

            usernameEditText.visibility = View.GONE
            passwordEditText.visibility = View.GONE
            emailEditText.visibility = View.GONE
            phoneEditText.visibility = View.GONE

            saveButton.visibility = View.GONE
            editButton.text = "修改"
        }
    }

    /**
     * 保存用户信息
     */
    private fun saveUserInfo() {
        val email = emailEditText.text.toString().trim()
        val phone = phoneEditText.text.toString().trim()
        val username = usernameEditText.text.toString().trim()
        val password = passwordEditText.text.toString().trim()

        // 检查输入
        if (email.isEmpty() || phone.isEmpty() || username.isEmpty() || password.isEmpty()) {
            Toast.makeText(requireContext(), "所有字段均不能为空", Toast.LENGTH_SHORT).show()
            return
        }

        // 获取 userId，确保与存储类型匹配
        val sharedPref = requireActivity().getSharedPreferences("user_prefs", Context.MODE_PRIVATE)
        val userId = sharedPref.getLong("userId", -1L)  // 使用 getLong 读取 userId，默认值为 -1L

        if (userId == -1L) {
            Toast.makeText(requireContext(), "用户未登录", Toast.LENGTH_SHORT).show()
            return
        }

        // 构建更新请求对象
        val updateRequest = UpdateUserRequest(
            username = username,
            password = password,
            email = email,
            phone = phone
        )

        // 打印请求数据
        Log.d("SaveUserInfo", "userId: $userId, updateRequest: $updateRequest")

        // 调用 Retrofit API 更新用户数据
        val apiService = RetrofitClient.instance.create(ApiService::class.java)
        apiService.updateUser(userId, updateRequest).enqueue(object : Callback<UpdateResponse> {
            override fun onResponse(call: Call<UpdateResponse>, response: Response<UpdateResponse>) {
                if (response.isSuccessful && response.body() != null) {
                    val updateResponse = response.body()
                    if (updateResponse?.success == true) {
                        // 更新成功
                        Toast.makeText(requireContext(), "信息更新成功", Toast.LENGTH_SHORT).show()

                        // 更新本地缓存
                        sharedPref.edit().apply {
                            putString("username", username)
                            putString("email", email)
                            putString("phone", phone)
                            apply()
                        }

                        // 重新加载用户数据并更新UI
                        fetchUserData()

                        // 切换回非编辑模式
                        isEditing = false
                        setEditMode(false)
                    } else {
                        Toast.makeText(requireContext(), "更新失败: ${updateResponse?.message}", Toast.LENGTH_SHORT).show()
                    }
                } else {
                    Toast.makeText(requireContext(), "请求失败: ${response.message()}", Toast.LENGTH_SHORT).show()
                    Log.e("SaveUserInfo", "请求失败: ${response.errorBody()?.string()}")
                }
            }

            override fun onFailure(call: Call<UpdateResponse>, t: Throwable) {
                Toast.makeText(requireContext(), "网络错误: ${t.message}", Toast.LENGTH_SHORT).show()
                Log.e("SaveUserInfo", "网络错误", t)
            }
        })
    }

    /**
     * 从服务器加载用户数据
     */
    private fun fetchUserData() {
        val sharedPref = requireActivity().getSharedPreferences("user_prefs", Context.MODE_PRIVATE)
        val userId = sharedPref.getLong("userId", -1L)  // 使用一致的 key

        Log.d("ProfileFragment", "fetchUserData called, userId: $userId")  // 打印 userId

        if (userId == -1L) {
            Toast.makeText(requireContext(), "用户未登录", Toast.LENGTH_SHORT).show()
            return
        }

        // 调用 Retrofit 接口获取用户数据
        val apiService = RetrofitClient.instance.create(ApiService::class.java)
        apiService.getUserById(userId).enqueue(object : Callback<UserModel> {
            override fun onResponse(call: Call<UserModel>, response: Response<UserModel>) {
                if (response.isSuccessful) {
                    val user = response.body()
                    if (user != null) {
                        // 如果 email 或 phone 字段为 null，显示默认值
                        val email = user.email ?: "未设置"
                        val phone = user.phone ?: "未设置"

                        // 更新 UI
                        usernameTextView.text = "用户名：${user.username}"
                        scoreTextView.text = "分数：${user.score}"
                        emailTextView.text = "邮箱：$email"
                        phoneTextView.text = "电话：$phone"

                        // 设置编辑框的初始值
                        usernameEditText.setText(user.username)
                        emailEditText.setText(email)
                        phoneEditText.setText(phone)
                    } else {
                        // 打印调试日志
                        Log.e("fetchUserData", "响应体为空，无法加载用户数据")
                        Toast.makeText(requireContext(), "无法加载用户数据", Toast.LENGTH_SHORT).show()
                    }
                } else {
                    // 打印调试信息
                    Log.e("fetchUserData", "响应失败: ${response.code()}, 错误信息: ${response.errorBody()?.string()}")
                    Toast.makeText(requireContext(), "无法加载用户数据", Toast.LENGTH_SHORT).show()
                }
            }

            override fun onFailure(call: Call<UserModel>, t: Throwable) {
                Toast.makeText(requireContext(), "网络错误: ${t.message}", Toast.LENGTH_SHORT).show()
            }
        })
    }

    /**
     * 退出登录
     */
    private fun logout() {
        val sharedPref = requireActivity().getSharedPreferences("user_prefs", Context.MODE_PRIVATE)
        sharedPref.edit().clear().apply()

        startActivity(Intent(requireContext(), LoginActivity::class.java))
        requireActivity().finish()
    }
}






